﻿using System;
using System.Web.Mvc;

namespace Matrix.MaKaYunShang.MagWeb
{
    /// <summary>
    /// 用户登录验证
    /// <para>如果不需要处理用户登录，则请指定AllowAnonymousAttribute属性</para>
    /// </summary>
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
    public class AuthorizationAttribute : FilterAttribute, IAuthorizationFilter
    {
        /// <summary>
        /// 处理用户登录
        /// </summary>
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext.HttpContext == null)
            {
                throw new Exception("此特性只适合于Web应用程序使用！");
            }
            else
            {
                var authSaveType = System.Configuration.ConfigurationManager.AppSettings["AuthSaveType"] ?? "Cookie";
                var userUrl = System.Configuration.ConfigurationManager.AppSettings["AuthUserUrl"];
                switch (authSaveType.ToUpper())
                {
                    case "SESSION":
                        if (filterContext.HttpContext.Session == null)
                        {
                            throw new Exception("服务器Session不可用！");
                        }
                        else if (!filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true)
&& !filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true))
                        {
                            if (filterContext.HttpContext.Session["user"] == null)
                            {
                                string url = string.Empty;
                                try { url = System.Web.HttpContext.Current.Request.Url.ToString(); } catch { }
                                filterContext.Result = new RedirectResult(userUrl + "?returnurl=" + url);
                            }
                        }
                        break;
                    case "COOKIE":
                        if (!filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true)
&& !filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true))
                        {
                            if (filterContext.HttpContext.Request.Cookies["user"] == null)
                            {
                                string url = string.Empty;
                                try { url = System.Web.HttpContext.Current.Request.Url.ToString(); } catch { }
                                filterContext.Result = new RedirectResult(userUrl + "?returnurl=" + url);
                            }
                        }
                        break;
                    default:
                        throw new ArgumentNullException("用于保存登录信息的方式不能为空，只能为【Cookie】或者【Session】！");
                }
            }
        }
    }
}